<?php

function get_my_shop($creat=1){//获取我的门店信息
global $conn,$cfg,$redis,$user,$set;
$list=r_get('my_shop_'.$user['id']);
if($list){return $list;}
$sql='select * from '.$cfg['e'].'shop where user_id="'.$user['id'].'" order by id asc limit 1';
$l=db1($sql);
if(!$l){
if($creat){//创建门店
$arr['user_id']=$user['id'];
$arr['logo']=$user['logo'];
$arr['shop_name']=base64($user['nickname'].'的小店',1);
$arr['date']=time();
if($user['pro']){
$arr['pro']=$user['pro'];$arr['city']=$user['city'];$arr['dist']=$user['dist'];
}
$arr['state']=0;
if($user['phone']){$arr['phone']=$user['phone'];}
$id=insert($cfg['e'].'shop',$arr);
$arr['id']=$id;
$l=$arr;
$arrs['shop_id']=$id;
update($cfg['e'].'users',$arrs,'where id="'.$user['id'].'"');

}

}
$l['shop_name']=base64($l['shop_name']);

r_set('my_shop_'.$user['id'],$l,300);

return $l;
}



function get_gz_list($shop_id=0){//获取关注列表
global $cfg,$conn,$redis,$user;
if(!$user){return;}
if($redis){
$list=$redis->get('gz_'.$user['id']);
if($list){
$list=unserialize(out($list));
if(is_array($list)){return $list;}
}
}


$sql='select shop_id,need_post from '.$cfg['e'].'shop_gz where user_id="'.$user['id'].'" and state=1 ';
if($shop_id){$sql.=' and shop_id="'.$shop_id.'" ';}
$l=db($sql);
if(!$l){return;}
foreach($l as $v){
$re['item']['item_'.$v['shop_id']]=$v['need_post'];
$re['shop'][$v['shop_id']]=$v['shop_id'];
}

if($redis and $cfg['debug']!=1){r_set('gz_'.$user['id'],$re,300);}
return $re;
}








function get_my_order_num($state=1){//获取订单的数
global $conn,$redis,$user,$cfg;
if(!$user){return 0;}
//是否缓存

$sql='select count(id) as num  from '.$cfg['e'].'order where user_id="'.$user['id'].'" and state in ('.$state.') order by id desc';

$l=db1($sql);
if($l){return $l['num'];}else{return 0;}


}



function get_zt_addr($addr){//获取自提点
global $conn,$cfg,$shop,$redis;
if(!$addr){return;}
$sql='select * from '.$cfg['e'].'addr where shop_id="'.$shop['id'].'" and id in ('.$addr.'0)';
$l=db($sql);
if($l){
foreach($l as $v){
$list['item_'.$v['id']]=$v;
}
}
return $list;
}


function pro_num($data){//商品数量
if(!$data){return 0;}
$num=0;$is_wx=0;
foreach($data as $k=>$v){
if($v['item']){
foreach($v['item'] as $m=>$n){
if($n['num']==-1){$is_wx++;}else{$num+=$n['num'];}

}}else{

if($v['num']==-1){$is_wx++;}else{$num+=$v['num'];}

}
}
if($is_wx){return -1;}
return $num;
}
//构建活动虚拟人数
function virtual_people($param,$pro)
{
    //根据需要虚拟的订单数，拼接数据
    //Total：总金额
    //Date：时间
    //Nickname：用户名
    //Logo：用户头像
    //Num:数量
    global $cfg;
    $sql='select logo from '.$cfg['e'].'users ';
    $orderinfo=db($sql);
    $l=array();
    for($i=0;$i<=$param['virtual_people'];$i++){
        $l[$i]['total'] = mt_rand(1, 500);
        // 定义时间范围：昨天00:00:00到当前时间
        $start = $param['start'];      // 昨天开始时间戳
        $end = time();                        // 当前时间戳
        $l[$i]['time'] = date_ff(mt_rand($start, $end));
        $l[$i]['nickname'] =generate();
        $l[$i]['logo'] = getRandomNonOneLogo($orderinfo);
        $l[$i]['num'] = mt_rand(1, 20);
        if($pro){
            // 随机选择一个索引
            $randomKey = array_rand($pro);
            $l[$i]['pro'][] = $pro[$randomKey];
            $l[$i]['pro'][0]['num'] = mt_rand(1, 5);
        }

    }
    return $l;

}

/**
 * @param $data
 * @return array|int|mixed|string|null
 */
function getRandomNonOneLogo($data) {
    // 过滤出 logo 不为 '1' 的元素
    $filtered = array_filter($data, function($item) {
        return $item['logo'] !== 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132';
    });
    // 如果没有符合条件的元素，返回 null（可根据需求调整）
    if (empty($filtered)) {
        return null;
    }
    // 随机选择一个索引
    $randomKey = array_rand($filtered);
    // 返回随机元素
    return $filtered[$randomKey]['logo'];
}

function generate()
{
    static $generated = []; // 静态存储已生成昵称
    static $maxRetries = 50; // 最大重试次数防止死循环

    $nicknames = [
        '自然生灵' => [
            '动物系' => ['小鹿','云雀','鲸落','萤火','狐言','鹤唳'],
            '植物系' => ['青禾','莲舟','枫眠','梅熟','竹醉','荼蘼'],
            '天象系' => ['星垂','月晕','虹霓','霜降','露白','雪霁']
        ],
        '古风雅韵' => [
            '器物系' => ['砚寒','箫默','剑魄','琴心','棋魂','酒狂'],
            '典籍系' => ['诗禅','画引','书魂','乐隐','易骨','墨魂'],
            '意境系' => ['檐语','灯烬','牖影','砧声','蓑雨','笠云']
        ],
        '现代文艺' => [
            '食物系' => ['布丁','奶盖','芋圆','糯米','糖霜','椰果'],
            '色彩系' => ['黛青','月白','胭脂','鸦青','靛蓝','琥珀'],
            '器物系' => ['胶片','邮筒','台灯','钢琴','相机','书签']
        ],
        '二次元风' => [
            '幻想系' => ['魔法使','星之舟','梦旅人','时之歌','光之子','影之舞'],
            '萌系' => ['团子君','棉花糖','泡芙酱','芝士球','布丁姬','奶泡酱']
        ],
        '网络文化' => [
            '梗文化' => ['真香怪','柠檬精','鸽子王','复读姬','欧皇酱','非酋君'],
            '弹幕系' => ['前方高能','空降成功','全体起立','泪目','双厨狂喜','战术后仰']
        ]
    ];

    $retryCount = 0;
    do {
        // 动态组合逻辑
        $components = [];
        $structure = rand(1, 3); // 随机选择1-3个组件组合

        for ($i = 0; $i < $structure; $i++) {
            // 随机选择主类（带权重，优先选择前3类）
            $weightedMain = [
                '自然生灵' => 3,
                '古风雅韵' => 3,
                '现代文艺' => 3,
                '二次元风' => 2,
                '网络文化' => 1
            ];
            $mainCategory = weighted_random($weightedMain);

            // 随机选择子类
            $subCategories = array_keys($nicknames[$mainCategory]);
            $subCategory = $subCategories[array_rand($subCategories)];

            // 随机获取昵称
            $pool = $nicknames[$mainCategory][$subCategory];
            $components[] = $pool[array_rand($pool)];
        }

        // 添加连接符和后缀（30%概率）
        if (mt_rand(1, 10) <= 3) {
            $connectors = ['·', '_', 'の', '·'];
            $suffixes = ['物语', '札记', '手记', '日志', '纪行'];
            $components[] = $connectors[array_rand($connectors)] .
                $suffixes[array_rand($suffixes)];
        }

        // 组合最终昵称（支持2-4段式结构）
        $newName = implode(array_rand(['', '·', '_', '✦']) ?: '', $components);

        // 去重检查
        $isUnique = !isset($generated[$newName]);
        if (!$isUnique) $retryCount++;

    } while (!$isUnique && $retryCount < $maxRetries);

    // 强制重置机制（防止极端情况）
    if ($retryCount >= $maxRetries) {
        $generated = [];
        $newName = generate(); // 递归重置后重新生成
    }

    $generated[$newName] = true;
    if(mb_strlen($newName, 'UTF-8') > 1) {
        $firstChar = mb_substr($newName, 0, 1, 'UTF-8');
        return $firstChar . "***";
    }
}

// 加权随机选择函数
function weighted_random($weights) {
    $rand = mt_rand(1, (int)array_sum($weights));
    foreach ($weights as $item => $weight) {
        $rand -= $weight;
        if ($rand <= 0) return $item;
    }
    return array_rand($weights);
}

function get_hd_order($hd,$page=1,$cache=0){//获取活动的订单列表
global $conn,$cfg,$redis;
if($redis and $cache){
$list=$redis->get('_hd_'.$hd['id'].'_order_'.$page);
if($list){$list=unserialize(out($list));
if(is_array($list)){return $list;}
}
}
$page_num=10;
$start=($page-1)*$page_num;
$sql='select id,total,date,state,nickname,logo,num from '.$cfg['e'].'order where  hd_id="'.$hd['id'].'" ';
$sql.=' and state>0 ';
$sql.=' order by id desc limit '.$start.','.$page_num;
$l=db($sql);
if(!$l){return;}
foreach($l as $k=>$v){
$l[$k]['time']=date_ff($v['date']);
$l[$k]['pro']=get_order_pro($v['id']);
//对显示的个人信息进行分析并隐藏
$l[$k]['nickname']=base64($v['nickname']);
$l[$k]=get_hd_name($l[$k],$hd['show_name']);
}

if($redis){
r_set('_hd_'.$hd['id'].'_order_'.$page,$l,60);
}
return $l;
}

function get_hd_name($p,$ac){
switch($ac){
case 1:return $p;break;
case 2:$p['nickname']=mb_substr($p['nickname'],0,1).'***';break;
case 3:$p['nickname']='';break;
case 4:$p['logo']='';break;
case 5:$p['logo']='';$p['nickname']=mb_substr($p['nickname'],0,1).'***';break;
}
return $p;

}



function get_order_pro($id){//获取活动的订单数据
global $conn,$cfg,$redis;
if($redis){
$list=$redis->get('hd_order_'.$id.'_pro');
if($list){$list=unserialize(out($list));
if(is_array($list)){return $list;}
}
}
$sql='select id,title,img,price,num,total,c,info,state from '.$cfg['e'].'order_pro where order_id="'.$id.'" order by id asc';
$l=db($sql);
if($l){
foreach($l as $k=>$v){
$l[$k]['title']=base64($v['title']);
}
if($redis){
r_set('hd__order_'.$id.'_pro',$l,3600);
}
return $l;
}
}



function get_miao_pro($id,$cache=0){
global $conn,$cfg,$shop,$redis;
if($redis and $cache){
$quan=$redis->get('hd_'.$id.'_miao');
if($quan){$quan=unserialize(out($quan));
if(is_array($quan)){return $quan;}
}
}

$sql='select * from '.$cfg['e'].'pro where id="'.a($id).'"  and shop_id="'.$shop['id'].'"';
$l=db1($sql);

if($l){
if($l['img']){$l['img']=get_img($l['img'],'_240');}else{$l['img']=$cfg['no_img'];}
$l['title']=base64($l['title']);
if($redis and $cache){
r_set('hd_'.$id.'_miao',$l,500);
}
}
return $l;
}

function get_mz_pro($id,$cache=0){
global $conn,$cfg,$shop,$redis;
if($redis and $cache){
$quan=$redis->get('_hd_'.$id.'_mz');
if($quan){$quan=unserialize(out($quan));
if(is_array($quan)){return $quan;}
}
}

$sql='select * from '.$cfg['e'].'pro where id="'.a($id).'"  and shop_id="'.$shop['id'].'"';
$l=db1($sql);
if($l){
if($l['img']){$l['img']=get_img($l['img'],'_240');}else{$l['img']=$cfg['no_img'];}
$l['title']=base64($l['title']);
if($redis and $cache){
r_set('_hd_'.$id.'_mz',$l,500);
}
}
return $l;
}


function get_hd_my_quan($id){//获取用户的活动优惠券
global $conn,$cfg,$shop,$user;if(!$user){return;}
$sql='select * from '.$cfg['e'].'quan_get where shop_id="'.$shop['id'].'" and user_id="'.$user['id'].'" and hd_id="'.$id.'" ';
$sql.=' order by man asc';
$l=db($sql);
return $l;
}

function get_hd_quan($id,$ac=0){//$cache是否读取缓存 活动的优惠券
global $conn,$cfg,$shop,$redis;
//if($redis and $cache){
//$quan=$redis->get('adm_'.$adm['id'].'_hd_'.$id.'_quan');
//if($quan){$quan=unserialize(out($quan));
//if(is_array($quan)){return $quan;}
//}}

$sql='select * from '.$cfg['e'].'quan where  hd_id="'.a($id).'" ';
$sql.=' and state=1  ';
if(!$ac){
$sql.=' and num!=0 ';
}
$sql.=' order by price asc';

$l=db($sql);
if($l){
foreach($l as $k=>$v){
$v['price']=number_format($v['price'],0,'.','');
$v['man']=number_format($v['man'],0,'.','');
$q['item_'.$v['id']]=$v;
}    

if($redis and $cache){
//r_set('adm_'.$adm['id'].'_hd_'.$id.'_quan',$q,500);
}
return $q;
}

}

function get_pro_item($id){//获取商品的信息
global $conn,$cfg,$adm;
$sql='select * from '.$cfg['e'].'pro where id="'.$id.'"   ';
$l=db1($sql);
if(!$l){return;}
$l['title']=base64($l['title']);
if($l['data']){$l['data']=unserialize(out($l['data']));}
$l['info']=base64($l['info']);
if($l['img']){
$l['imgs']=get_imgs($l['img']);
$l['img']=get_img($l['img'],'_240');
}else{
$l['img']=$cfg['no_img'];
}
return $l;
}
function get_pros($pros,$zk=100,$ac=0 ,$title = null){//获取商品列表，用于编辑 zk折扣
    global $conn,$cfg,$shop,$redis,$hd,$user;
    if(!$pros){return;}
    foreach($pros as $v){$pro[]=$v['id'];}
    $ids=implode(',',$pro);
    $sql='select * from '.$cfg['e'].'pro where shop_id="'.$shop['id'].'" and id in ('.$ids.',0)   ';
    if($ac){$sql.=' and state=1 ';}
    if($title){$sql.=' and CONVERT(FROM_BASE64(title) USING utf8mb4) like "%'.$title.'%" ';}
    $sql.=' order by field(id,'.$ids.',0)';

    $l=db($sql);


    if($redis and $hd){
        $hd_cache=$redis->get('hdcache_'.$hd['id']);
        if($hd_cache){$hd_cache=unserialize(out($hd_cache));}
        if(!$hd_cache or !is_array($hd_cache)){$hd_cache=[];}
//print_r($hd_cache);
    }

    if(!$zk or !is_numeric($zk)){$zk=100;}

//err($sql);
    $zk=$zk/100;
    if($l){
        foreach($l as $k=>$v){$k_num++;
            $v['title']=base64($v['title']);
            if($v['html']){$v['html']=unserialize(out(base64($v['html'])));}
            if($v['data']){$v['data']=unserialize(out($v['data']));}
            $v['info']=base64($v['info']);
            if($v['img']){
                $v['imgs']=get_imgs($v['img']);
                $v['img']=get_img($v['img'],'_240');
            }else{
                $v['img']=$cfg['no_img'];
            }

            if($zk<1){//存在折扣
                $v['price']=number_format($v['price']*$zk,2,'.','');
                if($v['data']){
                    foreach($v['data'] as $t=>$x){
                        if(!$x['price']){$x['price']=$v['price'];}else{
                            $x['price']=number_format($x['price']*$zk,2,'.','');
                        }
                        $v['data'][$t]['price']=$x['price'];//价格
                        if($x['item']){
                            foreach($x['item'] as $m=>$n){
                                if($n['price']>0 and is_numeric($n['price'])){
                                    $n['price']=number_format($n['price']*$zk,2,'.','');
                                }else{$n['price']=0;}
                                $v['data'][$t]['item'][$m]['price']=$n['price'];

                            }
                        }
                    }
                }
            }//折扣

            if($hd_cache){//缓存中去掉商品库存
                if($v['data']){//存在参数
                    $total=0;$is_f1=0;//是否无限
                    foreach($v['data'] as $j=>$t){
                        if($t['item']){//存在子分类
                            $item_total=0;$item_f1=0;
                            foreach($t['item'] as $x=>$z){

                                $cache_key='pro_'.$v['id'].'_'.$j.'_'.$x;
                                $max=$z['num'];$num=0;
                                if($max>0){
                                    if($hd_cache[$cache_key]){
                                        foreach($hd_cache[$cache_key] as $m=>$n){
                                            if($n['date']<time()){unset($hd_cache[$cache_key][$m]);$need_cache++;}else{//超时，删除
                                                $num+=$n['num'];
                                            }
                                        }}//获取缓存数

                                    if(!$num or !is_numeric($num)){$num=0;}
                                    $max=$max-$num;
                                    if($max==0 or $max<-1){$max=0;}
                                    $v['data'][$j]['item'][$x]['num']=$max;//子商品类数量
                                    $item_total+=$max;//子总量
//echo $j.' '.$x.' '.$item_total.'<br>';
                                }else{
                                    if($max==-1){$is_f1++;$item_f1++;}//如果是无限，那么子总理也为无限
                                }

                            }

                            $v['data'][$j]['num']=$item_total;//子总量
                            if($item_f1>0){$v['data'][$j]['num']=-1;}//设置为无限

//二级分类分析
                        }else{//一级分类
                            $cache_key='pro_'.$v['id'].'_'.$j;
                            $max=$t['num'];$num=0;
                            if($max>0){
                                if($hd_cache[$cache_key]){
                                    foreach($hd_cache[$cache_key] as $m=>$n){
                                        if($n['date']<time()){unset($hd_cache[$cache_key][$m]);$need_cache++;}else{//超时，删除
                                            $num+=$n['num'];
                                        }

                                    }

                                }

                                if(!$num or !is_numeric($num)){$num=0;}
                                $max=$max-$num;
                                if($max==0 or $max<-1){$max=0;}
                                $v['data'][$j]['num']=$max;
                                $total+=$max;

                            }else{
                                if($max==-1){$is_f1++;}
                            }

                        }


                    }
                    $v['total']=$total;
                    if($is_f1>0){$v['total']=-1;}//是否无限数量

                }else{//不存在子分类
                    $max=$v['total'];$num=0;
                    $cache_key='pro_'.$v['id'];
                    if($max>0){
                        if($hd_cache[$cache_key]){//存在缓存数据
                            foreach($hd_cache[$cache_key] as $m=>$n){
                                if($n['date']<time()){unset($hd_cache[$cache_key][$m]);$need_cache++;}else{//超时，删除
                                    $num+=$n['num'];
                                }}
                            if(!$num or !is_numeric($num)){$num=0;}
                            $max=$max-$num;
                            if($max==0 or $max<-1){$max=0;}
                            $v['total']=$max;
                        }

                    }

                }

            }

            if($need_cache and $redis){
                $timeout=$hd['end']-time();
                if($timeout<=0){$timeout=3600;}
                r_set('hdcache_'.$hd['id'],$hd_cache,$timeout);
            }

            $v['xiangou_num'] = 1000;


            if($v['data']){//有规格时，统计的数量需要根据规格确定
                foreach($v['data'] as $j=>$t){
                    $xiangou_num = 0;
                    $v['data'][$j]['xiangou_num'] = 1000;
                    if($t['xiangou']){
                        $sql_order='select data  from '.$cfg['e'].'order where user_id="'.$user['id'].'"and hd_id="'.$hd['id'].'" order by id desc';
                        $order=db($sql_order);
                            foreach ($order as $val){
                                if($val['data']){$val['data']=unserialize(out($val['data']));}
                                foreach ($val['data']['pro'] as $ord){
                                    if($v['id'] == $ord['id']){
                                        //本产品限购加1
                                        $xiangou_num ++;
                                    }
                                }
                            }
                            $xiangou_num =$t['xiangou'] - $xiangou_num;
                            $v['data'][$j]['xiangou_num'] = $xiangou_num > 0 ? $xiangou_num : 0;


                    }
                }
                uasort($v['data'], 'sortByXiangou');

            }else{
                if($v['xiangou'] != '-1'){//限购商品，去确定用户是否购买过
                    $xiangou_num = 0;
                    $sql_order='select data  from '.$cfg['e'].'order where user_id="'.$user['id'].'"and hd_id="'.$hd['id'].'" order by id desc';
                    $order=db($sql_order);
                    foreach ($order as $val){
                        if($val['data']){$val['data']=unserialize(out($val['data']));}
                        foreach ($val['data']['pro'] as $ord){
                            if($v['id'] == $ord['id']){
                                //本产品限购加1
                                $xiangou_num ++;
                            }
                        }

                    }
                    $xiangou_num = $v['xiangou'] - $xiangou_num;
                    $v['xiangou_num'] = $xiangou_num > 0 ? $xiangou_num : 0;
                }
            }






            $v['p']=explode('.',$v['price']);


//if($ac){
//$re[]=$v;
//}else{
            $v['k']=$k_num;
$re['item_'.$v['id']]=$v;
//    $re['gongn']=$v;
//$re['name'] = $v.c;
//}


        }
    }
    return $re;
}
// 自定义比较函数
function sortByXiangou($a, $b) {
    // 如果两者相等，保持原顺序
    if ($a['xiangou_num'] === $b['xiangou_num']) return 0;

    // true 在前（返回负数），false 在后（返回正数）
    return ($a['xiangou_num'] && !$b['xiangou_num']) ? -1 : 1;
}

function get_pros_new($pros,$zk=100,$ac=0){//获取商品列表，用于编辑 zk折扣
global $conn,$cfg,$shop,$redis,$hd;
if(!$pros){return;}
foreach($pros as $v){$pro[]=$v['id'];}
$ids=implode(',',$pro);
$sql='select * from '.$cfg['e'].'pro where shop_id="'.$shop['id'].'" and id in ('.$ids.',0)   ';
if($ac){$sql.=' and state=1 ';}
$sql.=' order by field(id,'.$ids.',0)';

$l=db($sql);


if($redis and $hd){
$hd_cache=$redis->get('hdcache_'.$hd['id']);
if($hd_cache){$hd_cache=unserialize(out($hd_cache));}
if(!$hd_cache or !is_array($hd_cache)){$hd_cache=[];}
//print_r($hd_cache);
}

if(!$zk or !is_numeric($zk)){$zk=100;}

//err($sql);
$zk=$zk/100;
if($l){
foreach($l as $k=>$v){$k_num++;
$v['title']=base64($v['title']);
if($v['html']){$v['html']=unserialize(out(base64($v['html'])));}
if($v['data']){$v['data']=unserialize(out($v['data']));}
$v['info']=base64($v['info']);
if($v['img']){
$v['imgs']=get_imgs($v['img']);
$v['img']=get_img($v['img'],'_240');
}else{
$v['img']=$cfg['no_img'];
}

if($zk<1){//存在折扣
$v['price']=number_format($v['price']*$zk,2,'.','');
if($v['data']){
foreach($v['data'] as $t=>$x){
if(!$x['price']){$x['price']=$v['price'];}else{
$x['price']=number_format($x['price']*$zk,2,'.','');
}
$v['data'][$t]['price']=$x['price'];//价格
if($x['item']){
foreach($x['item'] as $m=>$n){
if($n['price']>0 and is_numeric($n['price'])){
$n['price']=number_format($n['price']*$zk,2,'.','');
}else{$n['price']=0;}
$v['data'][$t]['item'][$m]['price']=$n['price'];

}
}
}
}
}//折扣

if($hd_cache){//缓存中去掉商品库存
if($v['data']){//存在参数
$total=0;$is_f1=0;//是否无限
foreach($v['data'] as $j=>$t){
if($t['item']){//存在子分类
$item_total=0;$item_f1=0;
foreach($t['item'] as $x=>$z){

$cache_key='pro_'.$v['id'].'_'.$j.'_'.$x;
$max=$z['num'];$num=0;
if($max>0){
if($hd_cache[$cache_key]){
foreach($hd_cache[$cache_key] as $m=>$n){
if($n['date']<time()){unset($hd_cache[$cache_key][$m]);$need_cache++;}else{//超时，删除
$num+=$n['num'];
}
}}//获取缓存数

if(!$num or !is_numeric($num)){$num=0;}
$max=$max-$num;
if($max==0 or $max<-1){$max=0;}
$v['data'][$j]['item'][$x]['num']=$max;//子商品类数量
$item_total+=$max;//子总量
//echo $j.' '.$x.' '.$item_total.'<br>';
}else{
if($max==-1){$is_f1++;$item_f1++;}//如果是无限，那么子总理也为无限
}

}

$v['data'][$j]['num']=$item_total;//子总量
if($item_f1>0){$v['data'][$j]['num']=-1;}//设置为无限

//二级分类分析
}else{//一级分类
$cache_key='pro_'.$v['id'].'_'.$j;
$max=$t['num'];$num=0;
if($max>0){
if($hd_cache[$cache_key]){
foreach($hd_cache[$cache_key] as $m=>$n){
if($n['date']<time()){unset($hd_cache[$cache_key][$m]);$need_cache++;}else{//超时，删除
$num+=$n['num'];
}

}    

}

if(!$num or !is_numeric($num)){$num=0;}
$max=$max-$num;
if($max==0 or $max<-1){$max=0;}
$v['data'][$j]['num']=$max;
$total+=$max;

}else{
if($max==-1){$is_f1++;}
}

}


}
$v['total']=$total;
if($is_f1>0){$v['total']=-1;}//是否无限数量

}else{//不存在子分类
$max=$v['total'];$num=0;
$cache_key='pro_'.$v['id'];
if($max>0){
if($hd_cache[$cache_key]){//存在缓存数据
foreach($hd_cache[$cache_key] as $m=>$n){
if($n['date']<time()){unset($hd_cache[$cache_key][$m]);$need_cache++;}else{//超时，删除
$num+=$n['num'];
}}
if(!$num or !is_numeric($num)){$num=0;}
$max=$max-$num;
if($max==0 or $max<-1){$max=0;}
$v['total']=$max;
}

}

}

}

if($need_cache and $redis){
$timeout=$hd['end']-time();
if($timeout<=0){$timeout=3600;}
r_set('hdcache_'.$hd['id'],$hd_cache,$timeout);
}



$v['p']=explode('.',$v['price']);


//if($ac){
//$re[]=$v;
//}else{
$v['k']=$k_num;
//$re['item_'.$v['id']]=$v;
//    $re['gongn']=$v;
//$re['name'] = $v.c;
//}
    $category = $v['c'];
    // 初始化分类（如果不存在）
    if (!isset($re[$category])) {
        $re[$category] = [
            'name' => $category,
            'goods' => []
        ];
    }

    $re[$category]['goods'][] = $v;

}
}
return array_values($re);
}


function get_hd_msg($id,$page=1){
global $conn,$cfg,$shop,$redis;
if($redis){
$quan=$redis->get('adm_'.$shop['id'].'_hd_msg_'.$id.'_'.$page);
if($quan){$quan=unserialize(out($quan));
if(is_array($quan)){return $quan;}
}}
$page_num=10;$start=($page-1)*$page_num;

$sql='select count(id) as num from '.$cfg['e'].'msg where shop_id="'.$shop['id'].'" and hd_id="'.a($id).'" and state=1 ';
$num=db1($sql);
if($num){
$re['total']=$num['num'];

$sql='select * from '.$cfg['e'].'msg where shop_id="'.$shop['id'].'" and hd_id="'.a($id).'"  ';
$sql.=' and state=1 ';
$sql.=' order by id desc limit '.$start.','.$page_num;
$l=db($sql);

if($l){$re['page']=$page;$re['num']=count($l);
foreach($l as $k=>$v){
$v['nickname']=base64($v['nickname']);
$v['time']=date_ff($v['date']);
$v['msg']=base64($v['msg']);
$v['re']=base64($v['re']);
$re['item'][]=$v;
}
if($redis){
r_set('adm_'.$shop['id'].'_hd_msg_'.$id.'_'.$page,$re,300);
}
return $re;
}
}
}

function get_hd_shop($id){
global $conn,$cfg,$redis,$set;
if($redis){
$quan=$redis->get($cfg['path'].'hd_shop_'.$id);
if($quan){$quan=unserialize(out($quan));
if(is_array($quan)){return $quan;}
}}

$sql='select * from '.$cfg['e'].'shop where id="'.a($id).'"   ';
$l=db1($sql);
if(!$l){err('抱歉，没有找到相关门店信息');}
$l['shop_name']=base64($l['shop_name']);
if($l['bg']){$l['bg']=unserialize(out($l['bg']));}else{
$l['bg']=$set['app_bg'];
}
if($redis){r_set($cfg['path'].'hd_shop_'.$id,$l,600);}
return $l;
}




?>